package de.lazy.gui.components;
/**  
 * SOURCE: http://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing/61982#61982
 */

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.ActionListener;
import java.awt.geom.*;
import java.awt.image.*;

import javax.swing.*;

public class DraggableTabbedPane extends JTabbedPane {
		
	//constants
	public static final long serialVersionUID = 1L;
	private static final int LINEWIDTH = 3;
	private static final String NAME = "TabTransferData";
	private static GhostGlassPane s_glassPane = new GhostGlassPane();

	
	private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
	private final Rectangle2D m_lineRect = new Rectangle2D.Double();

	private final Color m_lineColor = new Color(0, 100, 255);
	private TabAcceptor m_acceptor = null;
	private boolean m_hasGhost = true;
	private boolean m_isDrawRect = false;
	private boolean draggable = true;

	public DraggableTabbedPane() {
		super();
		final DragSourceListener dsl = new DragSourceListener() {
			public void dragEnter(DragSourceDragEvent e) {
				
				e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
			}

			public void dragExit(DragSourceEvent e) {
				
				e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
				
				m_lineRect.setRect(0, 0, 0, 0);
				m_isDrawRect = false;
				s_glassPane.setPoint(new Point(-1000, -1000));
				s_glassPane.repaint();
			}

			public void dragOver(DragSourceDragEvent e) {
				//e.getLocation()
				//This method returns a Point indicating the cursor location in screen coordinates at the moment

				TabTransferData data = getTabTransferData(e);
				if (data == null) {
					e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
					return;
				} // if


				e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
			}

			public void dragDropEnd(DragSourceDropEvent e) {
				m_isDrawRect = false;
				m_lineRect.setRect(0, 0, 0, 0);
				// m_dragTabIndex = -1;

				if (hasGhost()) {
					s_glassPane.setVisible(false);
					s_glassPane.setImage(null);
				}
			}

			public void dropActionChanged(DragSourceDragEvent e) {
			}
		};

		final DragGestureListener dgl = new DragGestureListener() {
			public void dragGestureRecognized(DragGestureEvent e) {
				// System.out.println("dragGestureRecognized");

				Point tabPt = e.getDragOrigin();
				int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
				if (dragTabIndex < 0) {
					return;
				} // if

				initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
				
				try {
					e.startDrag(DragSource.DefaultMoveDrop,	new TabTransferable(DraggableTabbedPane.this, dragTabIndex, FLAVOR, NAME), dsl);
				} catch (InvalidDnDOperationException idoe) {
					idoe.printStackTrace();
				}
			}
		};

		//dropTarget =
		new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(this), true);
		new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
		m_acceptor = new TabAcceptor() {
			public boolean isDropAcceptable(DraggableTabbedPane a_component, int a_index) {
				return true;
			}
		};
	}

	
	public TabAcceptor getAcceptor() {
		return m_acceptor;
	}

	public void setAcceptor(TabAcceptor a_value) {
		m_acceptor = a_value;
	}

	public TabTransferData getTabTransferData(DropTargetDropEvent a_event) {		
		try {
			TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);				
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
		try {
			TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);				
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
		try {
			TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
				.getTransferable().getTransferData(FLAVOR);				
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;		
	}



	public Point buildGhostLocation(Point a_location) {
		Point retval = new Point(a_location);

		switch (getTabPlacement()) {
			case JTabbedPane.TOP: {
				retval.y = 1;
				retval.x -= s_glassPane.getGhostWidth() / 2;
			} break;

			case JTabbedPane.BOTTOM: {
				retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
				retval.x -= s_glassPane.getGhostWidth() / 2;
			} break;

			case JTabbedPane.LEFT: {
				retval.x = 1;
				retval.y -= s_glassPane.getGhostHeight() / 2;
			} break;

			case JTabbedPane.RIGHT: {
				retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
				retval.y -= s_glassPane.getGhostHeight() / 2;
			} break;
		} // switch

		retval = SwingUtilities.convertPoint(DraggableTabbedPane.this,
				retval, s_glassPane);
		return retval;
	}


	public void setPaintGhost(boolean flag) {
		m_hasGhost = flag;
	}

	public boolean hasGhost() {
		return m_hasGhost;
	}

	/**
	 * returns potential index for drop.
	 * @param a_point point given in the drop site component's coordinate
	 * @return returns potential index for drop.
	 */
	public int getTargetTabIndex(Point a_point) {
		boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
				|| getTabPlacement() == JTabbedPane.BOTTOM;

		// if the pane is empty, the target index is always zero.
		if (getTabCount() == 0) {
			return 0;
		} // if

		for (int i = 0; i < getTabCount(); i++) {
			Rectangle r = getBoundsAt(i);
			if (isTopOrBottom) {
				r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
			} else {
				r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
			} // if-else

			if (r.contains(a_point)) {
				return i;
			} // if
		} // for

		Rectangle r = getBoundsAt(getTabCount() - 1);
		if (isTopOrBottom) {
			int x = r.x + r.width / 2;
			r.setRect(x, r.y, getWidth() - x, r.height);
		} else {
			int y = r.y + r.height / 2;
			r.setRect(r.x, y, r.width, getHeight() - y);
		} // if-else

		return r.contains(a_point) ? getTabCount() : -1;
	}

	public void convertTab(TabTransferData a_data, int a_targetIndex) {
		if(!draggable){
			return;
		}
		DraggableTabbedPane source = a_data.getTabbedPane();
		int sourceIndex = a_data.getTabIndex();
		

		if (sourceIndex < 0) {
			return;
		} // if

		Component cmp = source.getComponentAt(sourceIndex);
		Component tabCmp = source.getTabComponentAt(sourceIndex);
		
		
		String str = source.getTitleAt(sourceIndex);
		if (this != source) {
			source.remove(sourceIndex);

			if (a_targetIndex == getTabCount()) {
				addTab(str, cmp);
			} else {
				if (a_targetIndex < 0) {
					a_targetIndex = 0;
				} // if

				insertTab(str, null, cmp, null, a_targetIndex);
				if(tabCmp != null){
					setTabComponentAt(a_targetIndex, tabCmp);
				}

			} // if

			setSelectedComponent(cmp);
			return;
		} // if

		if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
			//System.out.println("press="+prev+" next="+next);
			return;
		} // if

		if (a_targetIndex == getTabCount()) {
			//System.out.println("last: press="+prev+" next="+next);
			source.remove(sourceIndex);
			
			
			addTab(str, cmp);
			if(tabCmp != null){
				setTabComponentAt(indexOfTab(str), tabCmp);
			}

			setSelectedIndex(getTabCount() - 1);
		} else if (sourceIndex > a_targetIndex) {
			//System.out.println("   >: press="+prev+" next="+next);
			source.remove(sourceIndex);
			insertTab(str, null, cmp, null, a_targetIndex);
			
			if(tabCmp != null){
				setTabComponentAt(a_targetIndex, tabCmp);
			}
			
			setSelectedIndex(a_targetIndex);
		} else {
			//System.out.println("   <: press="+prev+" next="+next);
			source.remove(sourceIndex);
			insertTab(str, null, cmp, null, a_targetIndex - 1);
			
			if(tabCmp != null){
				setTabComponentAt(a_targetIndex - 1, tabCmp);
			}
			
			setSelectedIndex(a_targetIndex - 1);
		}
	}

	public void initTargetLeftRightLine(int next, TabTransferData a_data) {		
		if (next < 0) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
			return;
		} // if

		if ((a_data.getTabbedPane() == this)
				&& (a_data.getTabIndex() == next
				|| next - a_data.getTabIndex() == 1)) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
		} else if (getTabCount() == 0) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
			return;
		} else if (next == 0) {
			Rectangle rect = getBoundsAt(0);
			m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
			m_isDrawRect = true;
		} else if (next == getTabCount()) {
			Rectangle rect = getBoundsAt(getTabCount() - 1);
			m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
					LINEWIDTH, rect.height);
			m_isDrawRect = true;
		} else {
			Rectangle rect = getBoundsAt(next - 1);
			m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
					LINEWIDTH, rect.height);
			m_isDrawRect = true;
		}
	}

	public void initTargetTopBottomLine(int next, TabTransferData a_data) {
		if (next < 0) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
			return;
		} // if

		if ((a_data.getTabbedPane() == this)
				&& (a_data.getTabIndex() == next
				|| next - a_data.getTabIndex() == 1)) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
		} else if (getTabCount() == 0) {
			m_lineRect.setRect(0, 0, 0, 0);
			m_isDrawRect = false;
			return;
		} else if (next == getTabCount()) {
			Rectangle rect = getBoundsAt(getTabCount() - 1);
			m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
					rect.width, LINEWIDTH);
			m_isDrawRect = true;
		} else if (next == 0) {
			Rectangle rect = getBoundsAt(0);
			m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
			m_isDrawRect = true;
		} else {
			Rectangle rect = getBoundsAt(next - 1);
			m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
					rect.width, LINEWIDTH);
			m_isDrawRect = true;
		}
	}

	private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
		//Point p = (Point) pt.clone();
		getRootPane().setGlassPane(s_glassPane);
		if (hasGhost()) {
			Rectangle rect = getBoundsAt(a_tabIndex);
			BufferedImage image = new BufferedImage(c.getWidth(),
					c.getHeight(), BufferedImage.TYPE_INT_ARGB);
			Graphics g = image.getGraphics();
			c.paint(g);
			image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
			s_glassPane.setImage(image);			
		} // if

		s_glassPane.setPoint(buildGhostLocation(tabPt));
		s_glassPane.setVisible(true);
	}

	private Rectangle getTabAreaBound() {
		Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
		return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		if (m_isDrawRect && draggable) {
			Graphics2D g2 = (Graphics2D) g;
			g2.setPaint(m_lineColor);
			g2.fill(m_lineRect);
		} // if
	}
	
	
	public void addComponentTab(Component tabButton, Component tabContent){
		
		JPanel container = new JPanel();
		container.setOpaque(false);
		container.add(tabButton);
		
		
		// add the container tab
		String tabId = "OPEN"+tabButton.hashCode();
		addTab(tabId, tabContent);
		
		//replace container tab with open button
		setTabComponentAt(indexOfTab(tabId), container);
	}
	
	
	
	  public static GhostGlassPane getS_glassPane() {
		return s_glassPane;
	}

	public boolean isDrawRect() {
		return m_isDrawRect;
	}

	public void setDrawRect(boolean drawRect){
		m_isDrawRect = drawRect;
	}
	
	public TabAcceptor getTabAcceptor() {
		return m_acceptor;
	}

	
	
	public boolean isDraggable() {
		return draggable;
	}

	public void setDraggable(boolean draggable) {
		this.draggable = draggable;
		this.m_hasGhost = draggable;
	}

	public static void main(String[] args) {
			
		
		    JFrame test = new JFrame("Tab test");
		    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		    test.setSize(400, 400);
	
		    DraggableTabbedPane tabs = new DraggableTabbedPane();
		    tabs.addTab("One", new JButton("One"));
		    tabs.addTab("Two", new JButton("Two"));
		    tabs.addTab("Three", new JButton("Three"));
		    tabs.addTab("Four", new JButton("Four"));
		    tabs.addComponentTab(new JButton("Test"), new JButton("11"));
		    //tabs.setDraggable(false);
		    
		    test.add(tabs);
		    test.setVisible(true);
		  }
	  
}


